<template>
  <div class="literature-list">
    <div class="header">
      <h2>文献列表</h2>
      <el-button v-if="userStore.userType !== 2" type="primary" @click="$router.push('/literature/upload')" round>
        <el-icon><Plus /></el-icon>
        上传文献
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <template #header>
        <div class="search-header">
          <span>搜索条件</span>
        </div>
      </template>
      <el-form :model="searchForm" label-width="80px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="8" :xs="24" :sm="12" :md="8">
            <el-form-item label="标题">
              <el-input 
                v-model="searchForm.title" 
                placeholder="请输入文献标题" 
                clearable 
                prefix-icon="Search"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24" :sm="12" :md="8">
            <el-form-item label="作者">
              <el-input 
                v-model="searchForm.authors" 
                placeholder="请输入作者" 
                clearable 
                prefix-icon="User"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24" :sm="12" :md="8">
            <el-form-item label="关键词">
              <el-input 
                v-model="searchForm.keywords" 
                placeholder="请输入关键词" 
                clearable 
                prefix-icon="Key"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 管理员筛选条件 -->
        <el-row :gutter="20" v-if="userStore.userType === 2">
          <el-col :span="8" :xs="24" :sm="12" :md="8">
            <el-form-item label="识别状态">
              <el-select 
                v-model="searchForm.recognitionStatus" 
                placeholder="请选择识别状态" 
                clearable
                style="width: 100%"
              >
                <el-option label="待处理" value="0"></el-option>
                <el-option label="识别中" value="1"></el-option>
                <el-option label="已识别" value="2"></el-option>
                <el-option label="识别失败" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <el-button type="primary" @click="searchLiterature">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 文献列表 -->
    <el-card class="literature-content">
      <template #header>
        <div class="table-header">
          <span>文献数据</span>
          <div class="header-actions">
            <el-button 
              type="success" 
              size="small" 
              @click="refreshList"
              :loading="loading"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        v-loading="loading" 
        :data="literatureList" 
        style="width: 100%"
        stripe
        border
        highlight-current-row
      >
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="{ row }">
            <el-link 
              type="primary" 
              @click="$router.push(`/literature/detail/${row.id}`)"
              :underline="false"
            >
              {{ row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="authors" label="作者" width="150" />
        <el-table-column prop="keywords" label="关键词" width="200">
          <template #default="{ row }">
            <el-tag 
              v-for="keyword in row.keywords?.split(',')" 
              :key="keyword" 
              size="small" 
              style="margin-right: 5px;"
              type="info"
            >
              {{ keyword }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publicationDate" label="发表时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.publicationDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="journal" label="期刊" width="150" />
        <el-table-column prop="recognitionStatus" label="识别状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getRecognitionStatusType(row.recognitionStatus)">
              {{ getRecognitionStatusText(row.recognitionStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="$router.push(`/literature/detail/${row.id}`)"
              round
            >
              查看
            </el-button>
            <el-button 
              v-if="userStore.userType === 2 && (row.recognitionStatus === 0 || row.recognitionStatus === 3)"
              type="warning" 
              size="small" 
              @click="triggerRecognition(row)"
              round
            >
              识别
            </el-button>
            <el-button 
              v-else
              :type="row.isFavorite ? 'warning' : 'success'" 
              size="small" 
              @click="toggleFavorite(row)"
              round
            >
              {{ row.isFavorite ? '取消收藏' : '收藏' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        style="margin-top: 20px; justify-content: center;"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, User, Key } from '@element-plus/icons-vue'
import { literatureApi } from '@/api/literature'
import type { PageResult, Literature } from '@/api/literature'
import { useUserStore } from '@/stores/user'
import webSocketService from '@/utils/websocket'

// 响应式数据
const loading = ref(false)
const literatureList = ref<Literature[]>([])
const userStore = useUserStore()

const searchForm = reactive({
  title: '',
  authors: '',
  keywords: '',
  recognitionStatus: '' // 添加识别状态筛选字段
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 方法
const searchLiterature = () => {
  pagination.current = 1
  loadLiteratureList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    title: '',
    authors: '',
    keywords: '',
    recognitionStatus: '' // 重置识别状态筛选
  })
  searchLiterature()
}

const refreshList = () => {
  loadLiteratureList()
}

const loadLiteratureList = async () => {
  loading.value = true
  try {
    // 构造查询参数，只有当识别状态不为空时才传递
    const queryParams: any = {
      ...searchForm,
      current: pagination.current,
      size: pagination.size
    }
    
    // 如果识别状态为空字符串，则删除该字段
    if (!queryParams.recognitionStatus) {
      delete queryParams.recognitionStatus
    } else {
      // 将字符串转换为数字
      queryParams.recognitionStatus = parseInt(queryParams.recognitionStatus, 10)
    }
    
    const response: PageResult<Literature> = await literatureApi.getList(queryParams)
    
    literatureList.value = response.records
    pagination.total = response.total
    loading.value = false
  } catch (error) {
    console.error('加载文献列表失败:', error)
    ElMessage.error('加载文献列表失败: ' + (error instanceof Error ? error.message : '系统异常，请稍后重试'))
    loading.value = false
  }
}

const toggleFavorite = async (row: Literature) => {
  try {
    await literatureApi.toggleFavorite(row.id)
    row.isFavorite = !row.isFavorite
    ElMessage.success(row.isFavorite ? '收藏成功' : '取消收藏成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const triggerRecognition = async (row: Literature) => {
  try {
    await ElMessageBox.confirm(`确定要对文献"${row.title}"触发识别吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await literatureApi.triggerRecognition(row.id)
    ElMessage.success('识别任务已启动')
    
    // 刷新列表
    await loadLiteratureList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('触发识别失败: ' + (error instanceof Error ? error.message : '系统异常，请稍后重试'))
    }
  }
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  loadLiteratureList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadLiteratureList()
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  try {
    // 更健壮的日期解析方法
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) {
      // 尝试其他常见日期格式
      const formats = [
        'yyyy-MM-dd HH:mm:ss',
        'yyyy-MM-ddTHH:mm:ss',
        'yyyy-MM-dd HH:mm:ss.SSS',
        'yyyy-MM-ddTHH:mm:ss.SSSZ'
      ]
      
      for (const format of formats) {
        // 尝试解析ISO格式的日期字符串
        const isoDate = new Date(dateStr.replace(' ', 'T'))
        if (!isNaN(isoDate.getTime())) {
          return isoDate.toLocaleDateString('zh-CN')
        }
      }
      
      return dateStr // 如果所有方法都失败，返回原始字符串
    }
    return date.toLocaleDateString('zh-CN')
  } catch (e) {
    // 如果解析失败，尝试直接返回原始字符串
    return dateStr || '-'
  }
}

const getRecognitionStatusType = (status: number) => {
  // 修改状态1和状态2都显示为已识别的样式
  if (status === 1 || status === 2) {
    return 'success' // 已识别的绿色样式
  }
  
  const types = ['info', 'success', 'warning', 'danger']
  return types[status] || 'info'
}

const getRecognitionStatusText = (status: number) => {
  // 修改状态1和状态2都显示为已识别的文本
  if (status === 1 || status === 2) {
    return '已识别'
  }
  
  const texts = ['待处理', '已识别', '识别中', '识别失败']
  return texts[status] || '未知'
}

// WebSocket回调函数
const handleLiteratureStatusUpdate = (literatureId: number) => {
  console.log('收到文献状态更新通知，文献ID:', literatureId)
  // 刷新列表以显示最新的状态
  loadLiteratureList()
}

// 生命周期
onMounted(() => {
  loadLiteratureList()
  
  // 连接WebSocket并设置回调
  webSocketService.setOnLiteratureStatusUpdate(handleLiteratureStatusUpdate)
  webSocketService.connect()
})

onUnmounted(() => {
  // 断开WebSocket连接
  webSocketService.disconnect()
})
</script>

<style scoped>
.literature-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.search-header {
  font-weight: bold;
  color: #303133;
}

.literature-content {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
}

/* 添加表格内容字体颜色优化 */
:deep(.el-table__body td) {
  color: #333333 !important;
}

:deep(.el-table__body td .el-link) {
  color: #409eff !important;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .el-col {
    margin-bottom: 15px;
  }
}
</style>